$(function(){
    /**
     * 分页初始条件
     */
    var total_count = 1;//分页总记录数
    var total = 1;//分页总页面数
    var currentPage = 1;//当前页
    var pageSize = pageOption.pageSize;//每页显示的记录数
    var idList = [];//批量选择id所存的数组
    var root_url = $("#root_url").val();

    /**
     * 页面初始化
     */
    function init(){
        myPagination();
        bindEvent();
    }

    /**
     * 事件绑定
     */
    function bindEvent(){
        //根据条件查询订单信息
        $('.inner-section #search_btn').click(function() {
            render(true,1,pageSize);
            return false;
        });

        //enter键盘事件
        $(".inner-section .search-param-form input").keydown(function(event){
            event = event ? event: window.event;
            if(event.keyCode == 13){
                render(true,1,pageSize);
                return false;
            }
        });
    }

    /**
     * 获取模糊参数
     */
    function getSelectInfo(){
        var selectInfo = {};
        $.each($('#search-param-form').serializeArray(), function(i, field){
            selectInfo[field.name]=field.value;
        });
        JSON.stringify(selectInfo);
        return selectInfo;
    }
    /**
     * 分页显示方法
     */
    function myPagination(){
        render(true,1,pageSize);
        //调用公共分页方法
        pagination("#page-selection",{pageSize:pageSize,total:total},render);

    }
    /**
     * 分页动态渲染数据
     * @param async ajax请求是否异步
     * @param pageIndex 当前显示页
     * @param pageSize 每页显示记录数
     */
    function render(async,pageIndex,pageSize){
        var selectInfo = getSelectInfo();
        selectInfo.pageIndex = pageIndex;
        selectInfo.pageSize = pageSize;
        $.ajax({
            async:async,
            type:'post',
            url:'pagingOrder',
            data:selectInfo,//从1开始计数
            dataType:'json',
            success:function(result){
                var html ='';
                if(result.errorCode == 0){
                    total = result.data.pageInfo.total_page;
                    total_count = result.data.pageInfo.total_count;
                    $("#page-selection").bootpag({total:total,total_count:total_count});//重新计算总页数,总记录数

                    currentPage = result.data.pageInfo.current_page;
                    var myList = result.data.dataList;

                    html+='<tr>' +
                        '<th class="th1">序号</th>' +
                        '<th class="">单号</th>' +
                        '<th class="">头像</th>' +
                        '<th class="">昵称</th>' +
                        '<th class="">姓名</th>' +
                        '<th class="">电话</th>' +
                        '<th class="">栏目认证时间</th>' +
                        '<th class="">所选套餐</th>' +
                        '<th class="">套餐金额</th>' +
                        '<th class="">申请退款时间</th>' +
                        '<th class="">审核状态</th>' +
                        '<th class="">退款状态</th>' +
                        '<th class="">实退金额</th>' +
                        '<th class="">操作</th>' +
                        '</tr>';
                    var colspan = $(html).find("th").length;
                    for(var i = 0; i < myList.length;i++){
                        var obj = myList[i];
                        var num = (pageIndex-1)*pageSize + i+1;
                        var id = obj.id;
                        var checked = (idList.indexOf(id) >= 0) ? "checked":"";//判断当前记录先前有没有被选中

                        var state_text = '待审核';
                        if (obj.audit_state == 1) state_text = '同意';
                        if (obj.audit_state == 2) state_text = '退款';

                        var refund_state_text = '';
                        if (obj.refund_state == 1) refund_state_text = '退款成功';
                        if (obj.refund_state == 2) refund_state_text = '<span style="cursor: pointer;color: red" data-info="'+obj.error_info+'" class="refund_fail">退款失败</span>';

                        var head_img_url_html = '--'
                        if (obj.head_img_url != null) {
                            head_img_url_html = '<img src="'+obj.head_img_url+'" width="45" height="45" />'
                        }

                        var refund_html = ''
                        if ((obj.audit_state == 1 && obj.refund_state == 0) || obj.refund_state == 2) {
                            refund_html = '<a href="javascript:;" class="refundOrder" data-id="' + id + '">退款</a>'
                        }

                        var audit_order_html = '';
                        if (obj.audit_state == 0) {
                            audit_order_html = '<a href="javascript:;" data-id="' + id + '" class="auditStatus" style="color: #00a0e9">审核</a>';
                        }

                        var order = null;
                        var order_add_time = '';
                        var order_amount = '';
                        if (obj.order != null) {
                            order_add_time = obj.order.add_time;
                            order_amount = obj.order.amount;
                        }

                        html += '<tr>'
                            + '<td class="th1">' + num + '</td>'
                            + '<td class="">' + obj.code + '</td>'
                            + '<td class="">' + head_img_url_html + '</td>'
                            + '<td class="">' + obj.nick_name + '</td>'
                            + '<td class="">' + obj.username + '</td>'
                            + '<td class="">' + obj.mobile + '</td>'
                            + '<td class="">' + order_add_time + '</td>'
                            + '<td class="">' + obj.order.package_info.title + '</td>'
                            + '<td class="">' + order_amount + '</td>'
                            + '<td class="">' + obj.add_time + '</td>'
                            + '<td class="">' + state_text + '</td>'
                            + '<td class="">' + refund_state_text + '</td>'
                            + '<td class="">' + (obj.refund_amount || '') + '</td>'
                            + '<td class="">'
                            + refund_html
                            + audit_order_html
                            + '</td>'
                            + '</tr>';
                    }

                    if(myList.length == 0){
                        html += '<tr><td colspan="'+colspan+'"><p class="text-danger">暂无数据。</p></td></tr>';
                        $("#list-table tbody").html(html);
                    }else{
                        $("#list-table tbody").html(html);
                        myCheck();
                        batchSelect(idList,".inner-section #list-table .select-all",".inner-section #list-table .select-single");

                        //审核
                        $("#list-table .auditStatus").click(auditStatus);
                        //退款
                        $("#list-table .refundOrder").click(refundOrder);
                        //信息
                        $("#list-table .refund_fail").click(showMsg);
                    }
                }else{
                    responseTip(result.errorCode,result.errorInfo,1500);
                }
            },
            error:errorResponse
        });
    }

    function showMsg () {
        var that = $(this)
        var info = that.attr('data-info');
        layer.tips(info, '.refund_fail', {
            tips: [1, '#3595CC'],
            time: 4000
        });
    }

    // 审核
    function auditStatus() {
        var that = $(this)
        layer.confirm('请选择审核状态?', {
            title: '提示',
            btn: ['通过审核', '审核失败'],
            btn1: function (index, layero) {
                agree(that, index, layero)
            },
            btn2: function (index) {
                reject(that, index)
            },
        })
    }

    // 审核同意
    function agree(that, index, layero) {
        var id = that.attr("data-id");
        $.ajax({
            type: "post",
            url: '../Refund/auditStatus',
            data: {
                "id": id, 'state': 1
            },
            dataType: 'json',
            success: function (json, statusText) {
                if (json.errorCode == 0) {
                    if (currentPage != 1 && total_count % pageSize == 1) {//非首页且末页记录数为1时
                        currentPage = currentPage - 1;
                    }
                    render(true, currentPage, pageSize);
                } else {
                    responseTip(json.errorCode, json.errorInfo, 1500);
                }
            }
        })
        layer.closeAll();
    }

    // 审核拒绝
    function reject(that, index) {
        var id = that.attr("data-id");
        layer.closeAll();
        layer.prompt({title: '原因', formType: 2}, function (reason, index) {
            if (reason == '') {
                return false;
            }
            $.ajax({
                type: "post",
                url: '../Refund/auditStatus',
                data: {
                    "id": id, 'state': 2, 'reason': reason
                },
                dataType: 'json',
                success: function (json, statusText) {
                    layer.closeAll();
                    if (json.errorCode == 0) {
                        if (currentPage != 1 && total_count % pageSize == 1) {//非首页且末页记录数为1时
                            currentPage = currentPage - 1;
                        }
                        render(true, currentPage, pageSize);
                    } else {
                        responseTip(json.errorCode, json.errorInfo, 1500);
                    }
                }
            })
        });
    }


    // 退款
    function refundOrder(){
        var that = $(this)
        layer.confirm('确认退款么?',{
            title:'提示',
            btn:['退款','取消'],
            btn1:function (index,layero) {
                agreeRefund(that,index,layero)
            },
            btn2:function (index) {

            },
        })
    }

    function agreeRefund(that,index,layero) {
        var id = that.attr("data-id");
        layer.closeAll();
        layer.prompt({title: '退款金额', formType: 2}, function (money, index) {
            if (money == '') {
                return false;
            }
            $.ajax({
                type:"post",
                url:'../Refund/agreeRefundByVideoAuth',
                data:{
                    "id":id, 'money': money
                },
                dataType:'json',
                success:function(json,statusText){
                    if(json.errorCode == 0){
                        if(currentPage !=1 && total_count % pageSize == 1){//非首页且末页记录数为1时
                            currentPage = currentPage - 1;
                        }
                        render(true,currentPage,pageSize);
                    }else{
                        responseTip(json.errorCode,json.errorInfo,1500);
                    }
                }
            })
        });
    }
    
    init();
});